package com.xb.loan.util.binaryConvert.parse.str;


import com.xb.loan.util.binaryConvert.ConvertUtil;
import com.xb.loan.util.binaryConvert.config.ParseConfig;
import com.xb.loan.util.binaryConvert.parse.ParseAble;
import com.xb.loan.util.binaryConvert.parse.ParsePointer;

import java.nio.charset.Charset;


public class StringParser implements ParseAble<String> {

	private static Charset charset = Charset.forName("UTF8");
	
	@Override
	public String convert(byte[] b, ParsePointer pointer, Class<?> clazz, ParseConfig parseConfig) {
		// 读取长度
		int sizes = ConvertUtil.readSizes(b, pointer);
		
		if(sizes == 0){
			
			return null;
		}
		
		String str = new String(b,pointer.getPointer(),sizes,charset);
		// 指针向后移动长度个单位
		pointer.move(sizes);
		
		return str;
	}

	@Override
	public byte[] format(String obj,ParseConfig config) {
		
		if(obj == null){
			
			return new byte[]{0};
		}
		
		byte[] bytes = obj.getBytes(charset);
		
		byte[] sizes = ConvertUtil.convertSizes(bytes.length);
		// 格式化后长度=sizes+内容
		byte[] src = new byte[sizes.length + bytes.length];
		// 添加长度字段
		ConvertUtil.put(src, 0, sizes);
		// 添加内容
		ConvertUtil.put(src, sizes.length, bytes);
		
		return src;
	}
	
	public static void main(String[] args) {
		
		StringParser parser = new StringParser();
		
		String str = "中国";
		
		byte[] src = parser.format(str,null);
		
		System.out.println(parser.convert(src, new ParsePointer(0),String.class,null));
		
	}

}
